import { ts } from 'qvog-dsl';

import { rule } from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/no-this-alias-check.md';

const allowDestructuring = true;
const allowedNames: string[] = [];

export default rule<{ message: string }>()
    .match((node): node is ts.VariableDeclaration | ts.BinaryExpression => {
        return ts.isVariableDeclaration(node) || ts.isBinaryExpression(node);
    })
    .when((node, { props }) => {
        const children = node.getChildren();
        if (children.length === 0) {
            return false;
        }

        const lastNode = children[children.length - 1];
        if (lastNode.kind !== ts.SyntaxKind.ThisKeyword) {
            return false;
        }

        const firstNode = children[0];
        if (ts.isObjectBindingPattern(firstNode) || ts.isArrayBindingPattern(firstNode)) {
            if (!allowDestructuring) {
                props.message = 'Unexpected aliasing of members of \'this\' to local variables.';
            }
        } else {
            const name = firstNode.getText();
            if (allowedNames.indexOf(name) === -1) {
                props.message = 'Unexpected aliasing of \'this\' to local variable.';
            }
        }
        return true;
    })
    .report((node, { api, props }) => {
        api.report({
            location: api.getLocation(node.getChildren()[0]),
            severity: SEVERITY,
            description: props.message,
            docPath: DOC_PATH,
        });
    });
